import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import Moment from 'moment';
import {
    Row, Col, Card, Form, Input,
    Icon, Button, Dropdown, Menu, Select,
    InputNumber, DatePicker, Modal, message, Tabs,
    Divider, Tag, Table, Pagination, Spin, Upload
    , AutoComplete, Radio, Popconfirm,
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './CustomerDetails.less';
import querystring from 'querystring';
import { validatemobile } from '../../utils/utils';
import AddCustomer from '../../components/Falcon/Customer/AddCustomer';

const InputGroup = Input.Group;
const RadioGroup = Radio.Group;
const { Description } = DescriptionList;
const FormItem = Form.Item;
const Option = Select.Option;
const { TabPane } = Tabs;
const { MonthPicker, RangePicker } = DatePicker;
const monthFormat = 'YYYY-MM-DD';
const costomerRelationArray = ["本人", "父/母", "配偶", "子/女", "兄弟/姐妹", "其他"];
let recordCustomer = null;
/*
  客户管理
*/

@connect(({ customer }) => ({
    customer,
}))
@Form.create()
export default class CustomerDetails extends PureComponent {
    state = {
        addCustomerShow: false,
        modal1Visible: false,
        modal2Visible: false,
        Modal3Visible: false,
        id: '',
        searchFilters: {
            custName: '',
            idcard: '',
            phone: '',
        },
        flag: 0,
    };

    componentDidMount() {
        const { dispatch, location } = this.props;
        const params = querystring.parse(location.search.slice(1));
        this.setState({
            id: params.id,
        })
        dispatch({
            type: 'customer/getCustomerDetails',
            payload: {
                id: params.id,
            },
        });
        dispatch({
            type: 'customer/fetchCustomerRelation',
            payload: {
                customerId: params.id,
            },
        });
    }
    setModal3Visible(modal3Visible) {
        this.setState({ modal3Visible });
    }

    componentDidMountRelation(record) {
        const { dispatch } = this.props;
      
        dispatch({
            type: 'customer/getCustomerDetails',
            payload: {
                id: record.id,
            },
        });
        dispatch(routerRedux.push(`customer-details?id=${record.id}&state=1`));
        location.reload(true);
    }

    handleSearch = (e) => {
        // e.preventDefault();
        this.props.dispatch({
            type: 'customer/fetchCustomer',
            payload: {
                offset: 0,
                limit: 10,
                custName: this.state.searchFilters.custName,
                idcard: this.state.searchFilters.idcard,
                phone: this.state.searchFilters.phone,
            },
        });
    }

    handleSearchCustNameChange = (e) => {
        this.setState({
            searchFilters: {
                ...this.state.searchFilters,
                custName: e.target.value,
            }
        })
    }

    handleSearchIdcardChange = (e) => {
        this.setState({
            searchFilters: {
                ...this.state.searchFilters,
                idcard: e.target.value,
            }
        })
    }

    handleSearchPhoneChange = (e) => {
        this.setState({
            searchFilters: {
                ...this.state.searchFilters,
                phone: e.target.value,
            }
        })
    }
    //重置
    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
            searchFilters: {
                ...this.state.searchFilters,
                custName: '',
                idcard: '',
                phone: '',
            }
        });
        dispatch({
            type: 'customer/fetchCustomer',
            payload: {
                offset: 0,
                limit: 10,
            }
        });
    };
    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                        <FormItem label="客户姓名">
                            <Input placeholder="请输入" value={this.state.searchFilters.custName} onChange={this.handleSearchCustNameChange} />
                        </FormItem>
                    </Col>
                    <Col md={12} sm={24}>
                        <FormItem label="身份证号">
                            <Input placeholder="请输入" value={this.state.searchFilters.idcard} onChange={this.handleSearchIdcardChange} />
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={12} sm={24}>
                        <Button icon="plus" type='primary' onClick={this.hanleAddMaintenance}>添加</Button>
                    </Col>
                    <Col md={12} sm={24}>
                        <span className={styles.submitButtons} style={{ textAlign: 'right' }}>
                            <Button type="primary" htmlType="submit">查询</Button>
                            <Button style={{ marginLeft: 10 }} onClick={this.handleFormReset}>重置</Button>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    columns = [{
        title: '客户姓名',
        dataIndex: 'custName',
        key: 'custName',
    }, {
        title: '身份证号',
        dataIndex: 'idcard',
        key: 'idcard',
    }, {
        title: '联系电话',
        dataIndex: 'phone',
        key: 'phone',
    }, {
        title: '客户关系',
        dataIndex: 'relation',
        key: 'relation',
        render(val) {
            return costomerRelationArray[val];
        },
    }, {
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        render: (text, record) => (
            //0:未激活；1：正常；2：已启动；3：已暂停
            <Fragment>
                <a onClick={() => this.componentDidMountRelation(record)}>详情 </a>
                {/* <Link to={`customer-details?id=${record.id}&state=1`}>详情</Link> */}
                <Divider type="vertical" />
                <Popconfirm title="是否要删除此客户？" onConfirm={() => this.deleteCustomerRelation(record.id)}>
                    <a>删除</a>
                </Popconfirm>
            </Fragment>
        )
    },];

    columns_2 = [{
        title: '客户编号',
        dataIndex: 'custNo',
        key: 'custNo',
        align: 'center'
    }, {
        title: '客户姓名',
        dataIndex: 'custName',
        key: 'custName',
        align: 'center'
    }, {
        title: '身份证号',
        dataIndex: 'idcard',
        key: 'idcard',
        align: 'center'
    }, {
        title: '联系电话',
        dataIndex: 'phone',
        key: 'phone',
        align: 'center'
    }, {
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        align: 'center',
        render: (text, record) => (
            //0:未激活；1：正常；2：已启动；3：已暂停
            <Fragment>
                <a onClick={() => this.hanleSearchMaintenanceShow(record)} >选择</a>
                {/* onChange={this.hanleSearchMaintenanceShow(record.id)}  */}
            </Fragment>
        )
    },];

    hanleAddMaintenance = () => {
        this.setState({
            modal1Visible: true,
            addCustomerShow: true,
            modal2Visible: false,
        })
    }

    //选择关系人
    hanleSearchMaintenanceShow = (record) => {
        this.setState({
            modal3Visible: true,
            addCustomerShow: true,
            modal2Visible: false,

        })
        recordCustomer = record
    }

    hanleSearchMaintenance = () => {
        const { dispatch, location } = this.props;
        const params = querystring.parse(location.search.slice(1));
        dispatch({
            type: 'customer/fetchCustomer',
            payload: {
                id: params.id,
                offset: 0,
                limit: 10,
            },
        });
        this.setState({
            modal2Visible: true,
        })
    }

    handleAddCustomerOnOK = () => {
        const { dispatch } = this.props;
        const form = this.formRef.props.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            form.resetFields();
            this.props.dispatch({
                type: 'customer/createCustomerRelation',
                payload: {
                    id: this.state.id,
                    ...values,
                },
                callback: () => {
                    const { customer: { customerResult, customerLoading } } = this.props;
                    if (customerResult.code == '200') {
                        message.success("添加成功")
                        this.setState({
                            modal1Visible: false
                        })
                        dispatch({
                            type: 'customer/fetchCustomerRelation',
                            payload: {
                                customerId: this.state.id,
                            },
                        });
                    } else {
                        message.error(customerResult.message)
                    }
                }
            })
            this.setState({
                modal3Visible: false,
            })
        });
    }


    handleOnCancel = () => {
        this.setState({
            modal1Visible: false
        })
    }

    handleOnCancel_2 = () => {
        this.setState({
            modal2Visible: false
        })
    }

    handleOnCancel_3 = () => {
        this.setState({
            modal3Visible: false
        })
    }

    handleSubmitkey1 = () => {
        const { validateFieldsAndScroll } = this.props.form;
        validateFieldsAndScroll((error, values) => {
            if (!error) {
                this.props.form.resetFields();

                this.props.dispatch({
                    type: 'customer/updateCustomerDetails',
                    payload: {
                        id: this.state.id,
                        flag: this.state.flag,
                        ...values,
                    },
                    callback: () => {
                        const { dispatch } = this.props;
                        const { customer: { customerResult } } = this.props;
                        if (customerResult.code == 200) {
                            //message.success("提交成功")
                            dispatch({
                                type: 'customer/getCustomerDetails',
                                payload: {
                                    id: this.state.id,
                                },
                            });
                        } else {
                            message.success(customerResult.message)
                        }
                    }
                })
            }
        })
    }

    handleSubmitkey2 = () => {
        const { validateFieldsAndScroll } = this.props.form;
        validateFieldsAndScroll((error, values) => {
            if (!error) {
                this.props.form.resetFields();
                this.props.dispatch({
                    type: 'customer/updateCustomerDetails',
                    payload: {
                        id: this.state.id,
                        flag: this.state.flag,
                        ...values,
                    }, callback: () => {
                        const { dispatch } = this.props;
                        const { customer: { customerResult } } = this.props;
                        if (customerResult.code == 200) {
                            //message.success("提交成功")
                            dispatch({
                                type: 'customer/getCustomerDetails',
                                payload: {
                                    id: this.state.id,
                                },
                            });
                        } else {
                            message.success(customerResult.message)
                        }
                    }
                })
            }
        })
    }

    deleteCustomerRelation = (id) => {
        const { dispatch, location } = this.props;
        const params = querystring.parse(location.search.slice(1));
        dispatch({
            type: 'customer/deleteCustomerRelation',
            payload: {
                relateId: id,
                id: params.id,
            },
            callback: () => {
                dispatch({
                    type: 'customer/fetchCustomerRelation',
                    payload: {
                        customerId: this.state.id,
                    },
                });
            },
        })
    }

    handleStandardTableChange = (e) => {
        // e.preventDefault();
        this.props.dispatch({
            type: 'customer/fetchCustomer',
            payload: {
                offset: (e.current - 1) * e.pageSize,
                limit: e.pageSize,
                custName: this.state.searchFilters.custName,
                idcard: this.state.searchFilters.idcard,
                phone: this.state.searchFilters.phone,
            },
        });
    }

    saveFormRef = (formRef) => {
        this.formRef = formRef;
    }

    onCancelSubmitkey1 = () => {
        this.setState({ flag: 1 })
    }
    onCancelSubmitkey2 = () => {
        this.setState({ flag: 2 })
    }


    render() {
        const { customer: { customerList, customerPage, customerDetailsObj, customerRelationList, customerLoading } } = this.props;
        const { getFieldDecorator, form, dispatch } = this.props;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 13 },
                md: { span: 7 },
            },
        };

        const submitFormLayout = {
            wrapperCol: {
                xs: { span: 24, offset: 0 },
                sm: { span: 7, offset: 8 },
            },
        };

        return (
            <PageHeaderLayout
                title="客户维护"
            >
                <Card>
                    {
                        // JSON.stringify(customerRelationList)
                    }
                    <Tabs tabPosition="top">
                        <TabPane tab="基本信息" key="1">
                            <Form onSubmit={this.handleSubmitkey1} style={{ marginTop: 10 }}>
                                <FormItem {...formItemLayout} label="客户姓名" >
                                    {
                                        form.getFieldDecorator('custName', {
                                            rules: [{
                                                required: true, message: '请输入姓名',
                                            }],
                                            initialValue: customerDetailsObj && customerDetailsObj.custName,
                                        })(
                                            <Input placeholder="请输入姓名" />
                                        )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="证件号码" >
                                    <InputGroup compact>
                                        {form.getFieldDecorator('idtype', {
                                            rules: [{
                                                required: true, message: '请选择证件类型',
                                            }],
                                            initialValue: customerDetailsObj && customerDetailsObj.idtype,
                                        })(
                                            <Select style={{ width: '30%' }} placeholder="请选择" onChange={this.onChangeSelect}>
                                                <Option value={1} >身份证</Option>
                                                <Option value={2}>其他</Option>
                                            </Select>
                                        )}
                                        {form.getFieldDecorator('idcard', {
                                            rules: [{
                                                required: true, message: '请输入证件号码',
                                            }],
                                            initialValue: customerDetailsObj && customerDetailsObj.idcard,
                                        })(
                                            <Input style={{ width: '70%' }} placeholder="请输入证件号码" />
                                        )}
                                    </InputGroup>
                                </FormItem>
                                <FormItem {...formItemLayout} label="性别" >
                                    {form.getFieldDecorator('sex', {
                                        rules: [{
                                            required: true, message: '请选择性别',
                                        }],
                                        initialValue: customerDetailsObj && customerDetailsObj.sex,
                                    })(
                                        <RadioGroup placeholder="请选择性别" >
                                            <Radio value={1}>男</Radio>
                                            <Radio value={2}>女</Radio>
                                        </RadioGroup>
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="年龄" >
                                    {form.getFieldDecorator('age', {
                                        rules: [{
                                            required: true,
                                        }],
                                        initialValue: customerDetailsObj && customerDetailsObj.age,
                                    })(
                                        <Input placeholder="请输入年龄" disabled/>
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="出生日期" >
                                    {form.getFieldDecorator('birthday', {
                                        rules: [{
                                            required: true, message: '请选择出生日期',
                                        }],
                                        initialValue: customerDetailsObj && customerDetailsObj.birthday ? Moment(customerDetailsObj.birthday) : Moment(),
                                    })(
                                        <DatePicker style={{ width: '100%' }} placeholder="请选择出生日期" format={monthFormat} />
                                    )}
                                </FormItem>

                                <FormItem {...formItemLayout} label="联系电话" >
                                    {
                                        form.getFieldDecorator('phone', {
                                            rules: [{
                                                required: true, message: '请输入    联系电话',
                                            }],
                                            initialValue: customerDetailsObj && customerDetailsObj.phone,
                                        })(
                                            <Input placeholder="请输入联系电话" />
                                        )}
                                </FormItem>
                                <FormItem {...submitFormLayout} style={{ marginTop: 30 }}>
                                    <Button type="primary" htmlType="submit" onCancel={this.onCancelSubmitkey1} loading={customerLoading}>
                                        保存
                                    </Button>
                                </FormItem>
                            </Form>
                        </TabPane>
                        <TabPane tab="详细信息" key="2">
                            <Form onSubmit={this.handleSubmitkey2} style={{ marginTop: 10 }}>
                                <FormItem {...formItemLayout} label="发证机关" >
                                    {
                                        form.getFieldDecorator('issueOrgan', {
                                            initialValue: customerDetailsObj && customerDetailsObj.issueOrgan,
                                        })(
                                            <Input placeholder="请输入发证机关" />
                                        )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="邮编" >
                                    {form.getFieldDecorator('postcode', {
                                        initialValue: customerDetailsObj && customerDetailsObj.postcode,
                                    })(
                                        <Input placeholder="请输入邮编" />
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="家庭住址" >
                                    {form.getFieldDecorator('residDetail', {
                                        initialValue: customerDetailsObj && customerDetailsObj.residDetail,
                                    })(
                                        <Input placeholder="请输入家庭住址" />
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="工作单位" >
                                    {form.getFieldDecorator('corp', {
                                        initialValue: customerDetailsObj && customerDetailsObj.corp,
                                    })(
                                        <Input placeholder="请输入工作单位" />
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="单位地址" >
                                    {form.getFieldDecorator('corpDetail', {
                                        initialValue: customerDetailsObj && customerDetailsObj.corpDetail,
                                    })(
                                        <Input placeholder="请输入单位地址" />
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout} label="教育程度" >
                                    {form.getFieldDecorator('education', {
                                        initialValue: customerDetailsObj && customerDetailsObj.education,
                                    })(
                                        <Select placeholder="请选择教育程度">
                                            <Option value={1}>未知</Option>
                                            <Option value={2}>博士及以上</Option>
                                            <Option value={3}>硕士研究生</Option>
                                            <Option value={4}>大学本科</Option>
                                            <Option value={5}>大学专科</Option>
                                            <Option value={6}>中专</Option>
                                            <Option value={7}>技校职高</Option>
                                            <Option value={8}>高中</Option>
                                            <Option value={9}>初中</Option>
                                            <Option value={10}>小学及以下</Option>
                                        </Select>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout} label="职业" >
                                    {form.getFieldDecorator('profession', {
                                        initialValue: customerDetailsObj && customerDetailsObj.profession,
                                    })(
                                        <Select placeholder="请选择职业">
                                            <Option value={1}>公务员</Option>
                                            <Option value={2}>学生</Option>
                                            <Option value={3}>事业单位员工</Option>
                                            <Option value={4}>其他行业职员</Option>
                                            <Option value={5}>军人</Option>
                                            <Option value={6}>自由职业者</Option>
                                            <Option value={7}>工人</Option>
                                            <Option value={8}>农名</Option>
                                        </Select>
                                    )}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout} label="婚姻状况" >
                                    {form.getFieldDecorator('maritalState', {
                                        initialValue: customerDetailsObj && customerDetailsObj.maritalState,
                                    })(
                                        <Select placeholder="请选择婚姻状况">
                                            <Option value={1}>已婚</Option>
                                            <Option value={2}>未婚</Option>
                                            <Option value={3}>离异</Option>
                                            <Option value={4}>丧偶</Option>
                                            <Option value={5}>分居</Option>
                                            <Option value={6}>其他</Option>
                                        </Select>
                                    )}
                                </FormItem>
                                <FormItem {...submitFormLayout} style={{ marginTop: 20 }}>
                                    <Button type="primary" htmlType="submit" onCancel={this.onCancelSubmitkey2} loading={customerLoading}>
                                        保存
                                    </Button>
                                </FormItem>

                            </Form>
                        </TabPane>

                        <TabPane tab="关系维护" key="3">
                            <Row gutter={{ md: 8, lg: 24, xl: 48 }} >

                                <Col md={24} sm={24}>
                                    <Button
                                        onClick={this.hanleSearchMaintenance}
                                        style={{ width: '100%', marginTop: '15px', marginBottom: '15px' }}
                                        type="dashed"
                                        icon="plus">
                                        添加关系人
                                    </Button>
                                </Col>
                                {/* <Col md={12} sm={24}>
                                    <Button
                                        onClick={this.hanleAddMaintenance}
                                        style={{ width: '100%', marginTop: '15px', marginBottom: '15px' }}
                                        type="dashed"
                                        icon="plus">
                                        添加关系人
                                    </Button>
                                </Col> */}
                            </Row>
                            <Table
                                dataSource={customerRelationList}
                                columns={this.columns}
                                loading={customerLoading}
                            >
                            </Table>
                        </TabPane>
                    </Tabs>
                </Card>
                <Modal
                    title="客户新增"
                    visible={this.state.modal1Visible}
                    onCancel={this.handleOnCancel}
                    onOk={this.handleAddCustomerOnOK}
                >
                    <AddCustomer marriageShow={true} isEdit={false} wrappedComponentRef={this.saveFormRef} />
                </Modal>
                <Modal
                    title="客户关系新增"
                    visible={this.state.modal3Visible}
                    onCancel={this.handleOnCancel_3}
                    onOk={this.handleAddCustomerOnOK}
                >
                    <AddCustomer marriageShow={true} isEdit={true} recordCustomer={recordCustomer && recordCustomer} wrappedComponentRef={this.saveFormRef} />
                </Modal>
                <Modal
                    title="客户列表"
                    width="800px"
                    visible={this.state.modal2Visible}
                    onCancel={this.handleOnCancel_2}
                    footer={null}
                >
                    <div className={styles.tableListForm}>
                        {this.renderSimpleForm()}
                    </div>
                    <Table
                        size="small"
                        dataSource={customerList}
                        pagination={customerPage}
                        columns={this.columns_2}
                        loading={customerLoading}
                        rowKey="id"
                        onChange={this.handleStandardTableChange}
                    />
                </Modal>

            </PageHeaderLayout>
        );
    }
}
